from lib.live.TLSSigAPI import TLSSigAPI
from apps.student.share import app_logger
import traceback
from lib.live.RequestHandler import RequestHandler
import random


class ImMain(object):

    def __init__(self):
        self.sdkappid = 1400595882
        self.key = '6d17375b836b62be432ad412ba04aec46e867e832870cfa1e6067addebd711df'
        self.url = 'https://console.tim.qq.com/'
        self.admins = ''

    def get_usersig(self, userid, roomid=None, roomstr=None, privilegeMap=42, type=1, expire=604800):
        """
        获取调用im接口时要用到的usersig参数
        :param userid: 用户唯一标识
        :param roomid: 房间id
        :param roomstr: 房间字符串id
        :param privilegeMap: 默认42 代表该 userid 拥有加入房间和接收音视频数据的权限，但不具备其他权限。
        :param type: 类型 1:用于签发TRTC和IM服务中必须要使用的UserSig鉴权票据  2: 用于签发 TRTC 进房参数中可选的 PrivateMapKey 权限票据。
                         3:用于签发 TRTC 进房参数中可选的 PrivateMapKey 权限票据。与2不同的是房间号类型不一样
        :param expire:
        :return:
        """
        try:
            api = TLSSigAPI(self.sdkappid, self.key)
            if type == 1:
                sig = api.genUserSig(userid)
            if type == 2:
                sig = api.genPrivateMapKey(userid, expire, roomid, 255)
            if type == 3:
                sig = api.genPrivateMapKeyWithStringRoomID(userid, expire, roomstr, 255)
            return sig
        except:
            err = traceback.format_exc()
            app_logger.error(err)
            return False

    def get_online_member_num(self, groupid):
        """
        获取直播群在线人数
        :param groupid:
        :return:
        """
        url = self.get_requrl('v4/group_open_http_svc/get_online_member_num', 'administrator')
        payload = {
            "GroupId": groupid,
        }
        req = RequestHandler()
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})

    def create_group(self, userid):
        """
        创建群
        请求url: v4/group_open_http_svc/create_group
        sdkappid: 创建应用时即时通信 IM 控制台分配的 SDKAppID
        identifier: 必须为 App 管理员帐号(账号类型)  administrator
        usersig: App 管理员帐号生成的签名
        random: 请输入随机的32位无符号整数，取值范围0 - 4294967295
        :return:
        """
        url = self.get_requrl('v4/group_open_http_svc/create_group', 'administrator')
        payload = {
            "Owner_Account": str(userid),
            "Type": "AVChatRoom",
            "Name": "momself_"+str(userid),
            "ApplyJoinOption": "FreeAccess"  # 申请加群处理方式 FreeAccess 表示允许无需审批自由加入群组
        }
        req = RequestHandler()
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})

    def get_group_info(self, group_list):
        """
        获取群信息
        :param group_list:
        :return:
        """
        url = self.get_requrl('v4/group_open_http_svc/get_group_info', 'administrator')
        payload = {
            "GroupIdList": group_list,
            "ResponseFilter": {
                "GroupBaseInfoFilter": [
                    "GroupId",
                    "ErrorCode",
                    "Type",
                    "Name",
                    "Introduction",
                    "Notification",
                    "CreateTime",
                    "NextMsgSeq",
                    "MemberNum",
                    "MaxMemberNum",
                    "ApplyJoinOption",
                    "Owner_Account"
                ]
            }
        }
        req = RequestHandler()
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})

    def forbid_send_msg(self, groupid, members, shutuptime=60):
        """
        批量禁言和取消禁言
        :param groupid:
        :param members:
        :return:{
                    "ActionStatus": "OK",
                    "ErrorInfo": "",
                    "ErrorCode": 0
                }
        """
        url = self.get_requrl('v4/group_open_http_svc/forbid_send_msg', 'administrator')
        payload = {
            "GroupId": groupid,
            "Members_Account": members,
            "ShutUpTime": shutuptime  # 为0时表示取消禁言 大于表示禁言时间
        }
        req = RequestHandler()
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})

    def get_group_shutted_uin(self, groupid):
        """
        获取被禁言群成员列表
        :param groupid: 群id
        :return:{
                    "ActionStatus": "OK",
                    "ErrorCode": 0,
                    "GroupId": "@TGS#2FZNNRAEU",
                    "ShuttedUinList": [ // 群组中被禁言的用户列表
                        {
                            "Member_Account": "tommy", // 用户 ID
                            "ShuttedUntil": 1458115189 // 禁言到的时间（使用 UTC 时间，即世界协调时间）
                        },
                        {
                            "Member_Account": "peter",
                            "ShuttedUntil": 1458115189
                        }
                    ]
                }
        """
        url = self.get_requrl('v4/group_open_http_svc/get_group_shutted_uin', 'administrator')
        payload = {
            "GroupId": groupid,
        }
        req = RequestHandler()
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})

    def send_group_msg(self, group_id, command, message):
        """
        在群组中发送普通消息
        :param group_id: 需要发送的群
        :param command: 自定义类型 9:推送商品 11:刷新api 12:刷新直播状态 13:发送虚拟数据 14:发送虚拟评论
        :param message: 自定义数据
        :return:
        """
        from random import randint
        url = self.get_requrl('v4/group_open_http_svc/send_group_msg', 'administrator')
        payload = {
            "GroupId": group_id,
            "Random": randint(0, 99999999),
            "MsgPriority": "High",
            "ForbidCallbackControl": [
                "ForbidBeforeSendMsgCallback",
                "ForbidAfterSendMsgCallback"
            ],
            "MsgBody": [
                {
                    "MsgType": "TIMCustomElem",
                    "MsgContent": {
                        "Data": '{"version": "1.0.0", "businessID": "av_live", "action": 301, "command": %s, "message": %s}'%(command, message),
                    }
                }
            ],
        }
        req = RequestHandler()
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})

    def send_group_system_notification(self, groupid, content):
        """
        在群组中发送系统通知（全员发送）
        :param groupid: 群id
        :param content: 系统通知内容
        :return:{
                  "ActionStatus": "OK",
                  "ErrorInfo": "",
                  "ErrorCode": 0
                }
        """
        url = self.get_requrl('v4/group_open_http_svc/send_group_system_notification', 'administrator')
        payload = {
            "GroupId": groupid,
            "Content": "Hello World" # 系统通知内容
        }
        req = RequestHandler()
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})

    def group_msg_recall(self, groupid, msgseq):
        """
        撤回群消息
        :param groupid:
        :param msgseq: [
                           {
                            "MsgSeq":100
                           },
                           {
                               "MsgSeq":101 #请求撤回的消息 seq
                           }
                       ]
        :return: {
                  "ActionStatus": "OK",
                  "ErrorInfo": "",
                  "ErrorCode": 0,
                  "RecallRetList":[
                      {
                          "MsgSeq":100,
                          "RetCode":10030
                      },
                      {
                          "MsgSeq":101, #单个被撤回消息的 seq
                          "RetCode":0 # 单个消息的被撤回结果：0表示成功；其它表示失败，参考下文错误码说明
                      }
                  ]
                }
        """
        url = self.get_requrl('v4/group_open_http_svc/group_msg_recall', 'administrator')
        payload = {
            "GroupId": groupid,
            "MsgSeqList": msgseq
        }
        req = RequestHandler()
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})

    def delete_group_msg_by_sender(self, groupid, sender):
        """
        撤回指定用户发送的消息
        :param groupid:
        :param sender:
        :return:
        """
        url = self.get_requrl('v4/group_open_http_svc/delete_group_msg_by_sender', 'administrator')
        payload = {
            "GroupId": groupid,
            "Sender_Account": sender
        }
        req = RequestHandler()
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})

    def account_import(self, identifier, nickname=None, faceurl=None):
        """
        创建导入管理员账号
        v4/im_open_login_svc/account_import
        :param identifier: 用户名，长度不超过32字节
        :param nickname: 用户昵称
        :param faceurl: 用户头像 URL
        :return:{
                   "ActionStatus":"OK",
                   "ErrorInfo":"",
                   "ErrorCode":0
                }
        """
        url = self.get_requrl('v4/im_open_login_svc/account_import', 'administrator')
        payload = {
            "Identifier": identifier,
            "Nick": nickname,
            "FaceUrl": faceurl
        }
        req = RequestHandler()
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})

    def account_check(self, userid):
        """
        查询帐号
        :param userid: 请求检查的帐号的 UserID
        :return:
        """
        url = self.get_requrl('v4/im_open_login_svc/account_check', 'administrator')
        payload = {"CheckItem": [{"UserID": userid}]}
        req = RequestHandler()
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})

    def all_member_push(self, payload):
        """
        全员推送---这个本接口包含全员/属性/标签推送，默认每天最多调用100次，每两次推送间隔必须大于1s。有特别频率需求的（如需提高频率），请在申请工单中说明。
        :param msgbody:
        :param msgtype:
        :param msgcontent:
        :return:
        """
        url = self.get_requrl('v4/all_member_push/im_push', 'administrator')
        req = RequestHandler()
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})

    def getappinfo(self):
        """
        拉取运营数据--拉取最近30天的运营数据
        :return:
        """
        url = self.get_requrl('v4/openconfigsvr/getappinfo', 'administrator')
        req = RequestHandler()
        return req.visit("post", url, json={}, headers={"content-type": "application/json"})

    def get_requrl(self, api, identifier, type=1):
        """
        获取im接口请求路径
        :param api: 请求api名
        :param identifier: 管理员账号
        :return:
        """
        random_str = random.randrange(1, 999999999, 9)
        usersig = self.get_usersig(identifier, type=type)
        url = '{}.{}?sdkappid={}&identifier={}&usersig={}&random={}&contenttype=json'.format(self.url, api, self.sdkappid,
                                                                                             identifier, usersig,
                                                                                             random_str)
        return url

    def destroy_group(self, group_id):
        """
        解散群组
        @param group_id:
        @return:
        """
        url = self.get_requrl('v4/group_open_http_svc/destroy_group', 'administrator')
        req = RequestHandler()
        payload = {"GroupId": str(group_id)}
        return req.visit("post", url, json=payload, headers={"content-type": "application/json"})
